<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>校园二手市场 - 收货地址管理</title>
    <style>
        :root {
            --primary-color: #4CAF50;
            --secondary-color: #66BB6A;
            --light-gray: #F5F5F5;
            --text-color: #212121;
            --sub-text: #757575;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
        }

        body {
            line-height: 1.6;
            color: var(--text-color);
            background-color: var(--light-gray);
            min-height: 100vh;
            padding-bottom: 60px;
            position: relative;
        }

        .header {
            background-color: var(--primary-color);
            color: white;
            padding: 1rem;
            text-align: center;
        }

        .content {
            flex: 1;
            padding-bottom: 80px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 1rem;
        }

        .address-management {
            background-color: #fff;
            padding: 1rem;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            margin-bottom: 1rem;
        }

        .user-info {
            margin-bottom: 1.5rem;
            padding: 1rem;
            background-color: var(--light-gray);
            border-radius: 8px;
            position: relative;
            display: none;
            /* 隐藏用户信息部分 */
        }

        .address-list {
            margin-top: 1rem;
        }

        .address-card {
            background-color: #fff;
            padding: 1rem;
            border-radius: 8px;
            margin-bottom: 1rem;
            position: relative;
            border: 1px solid #eee;
            transition: all 0.3s;
        }

        .address-card:hover {
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }

        .address-card.default {
            border-left: 4px solid var(--primary-color);
            background-color: #f8fff8;
        }

        .address-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 0.8rem;
            padding-bottom: 0.5rem;
            border-bottom: 1px dashed #eee;
        }

        .address-name {
            font-weight: bold;
            font-size: 1.1rem;
        }

        .address-phone {
            color: var(--sub-text);
            margin-left: 1rem;
        }

        .default-tag {
            background-color: var(--primary-color);
            color: white;
            padding: 0.2rem 0.5rem;
            border-radius: 4px;
            font-size: 0.8rem;
            margin-left: 0.5rem;
        }

        .address-detail {
            color: var(--text-color);
            margin-bottom: 0.8rem;
            line-height: 1.5;
        }

        .address-actions {
            display: flex;
            gap: 0.8rem;
        }

        .address-actions button {
            padding: 0.4rem 0.8rem;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 0.9rem;
            transition: all 0.2s;
        }

        .btn-edit {
            background-color: #e3f2fd;
            color: #1976d2;
        }

        .btn-delete {
            background-color: #ffebee;
            color: #e53935;
        }

        .btn-add {
            display: block;
            width: 100%;
            padding: 0.8rem;
            background-color: var(--primary-color);
            color: white;
            border: none;
            border-radius: 4px;
            text-align: center;
            cursor: pointer;
            margin-top: 1rem;
            font-size: 1rem;
            transition: background-color 0.3s;
        }

        .btn-add:hover {
            background-color: var(--secondary-color);
        }

        /* 地址编辑模态框样式 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0, 0, 0, 0.4);
        }

        .modal-content {
            background-color: #fefefe;
            margin: 15% auto;
            padding: 1.5rem;
            border: none;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            width: 90%;
            max-width: 500px;
            position: relative;
        }

        .close {
            color: #666;
            position: absolute;
            right: 1.5rem;
            top: 1rem;
            font-size: 1.5rem;
            font-weight: 400;
            cursor: pointer;
        }

        .close:hover,
        .close:focus {
            color: var(--text-color);
            text-decoration: none;
        }

        .modal-content h2 {
            text-align: center;
            color: var(--text-color);
            font-size: 1.2rem;
            margin-bottom: 1.5rem;
            padding-bottom: 0.5rem;
            border-bottom: 1px solid #eee;
        }

        .modal-content form {
            display: flex;
            flex-direction: column;
            gap: 1rem;
        }

        .form-group {
            display: flex;
            flex-direction: column;
        }

        .form-group label {
            margin-bottom: 0.3rem;
            font-size: 0.9rem;
            color: var(--text-color);
            font-weight: 500;
        }

        .form-group input,
        .form-group select {
            padding: 0.6rem 0.8rem;
            border: 1px solid #e0e0e0;
            border-radius: 4px;
            font-size: 0.9rem;
            background-color: #f9f9f9;
            transition: border-color 0.3s;
        }

        .form-group input:focus,
        .form-group select:focus {
            border-color: var(--primary-color);
            outline: none;
        }

        .form-actions {
            display: flex;
            justify-content: flex-end;
            gap: 0.5rem;
            margin-top: 1rem;
        }

        .form-actions button {
            padding: 0.6rem 1rem;
            border: none;
            border-radius: 4px;
            font-size: 0.9rem;
            font-weight: 500;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .btn-cancel {
            background-color: var(--light-gray);
            color: var(--text-color);
        }

        .btn-save {
            background-color: var(--primary-color);
            color: white;
        }

        .btn-save:hover {
            background-color: var(--secondary-color);
        }

        /* 导航栏CSS样式 */
.nav-bar {
    display: flex;
    justify-content: space-around;
    background-color: #fff;
    padding: 0.5rem;
    position: fixed;
    bottom: 0;
    width: 100%;
    margin: 0 auto;
    left: 50%;
    transform: translateX(-50%);
    box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1);
    border-radius: 12px 12px 0 0;
    z-index: 102;
}

.nav-bar a {
    color: var(--sub-text);
    text-decoration: none;
    padding: 0.5rem 1rem;
    display: flex;
    flex-direction: column;
    align-items: center;
    font-size: 0.8rem;
    transition: color 0.3s;
    position: relative;
}

.nav-bar a.active {
    color: var(--primary-color);
}

.nav-bar a.active::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    width: 60%;
    height: 3px;
    background-color: var(--primary-color);
    border-radius: 3px;
}

.nav-icon {
    width: 24px;
    height: 24px;
    position: relative;
    margin-bottom: 0.2rem;
}

.home-icon::before {
    content: "🏠";
}

.products-icon::before {
    content: "📦";
}

.publish-icon::before {
    content: "✏️";
}

.news-icon::before {
    content: "💬";
}

.account-icon::before {
    content: "👤";
}

.new-badge {
    position: absolute;
    top: 5px;
    right: 5px;
    background-color: #e74c3c;
    color: white;
    font-size: 0.6rem;
    padding: 0.2rem 0.4rem;
    border-radius: 10px;
    line-height: 1;
}

        .empty-state {
            text-align: center;
            padding: 2rem 0;
            color: #999;
        }

        .empty-state i {
            font-size: 3rem;
            color: #ccc;
            margin-bottom: 1rem;
        }

        /* 地图容器样式 */
        .map-container {
            width: 100%;
            height: 300px;
            margin-bottom: 1rem;
            border-radius: 8px;
            overflow: hidden;
            display: none;
        }

        .map-actions {
            display: flex;
            justify-content: space-between;
            margin-bottom: 1rem;
        }

        .btn-map {
            padding: 0.6rem 1rem;
            border: none;
            border-radius: 4px;
            font-size: 0.9rem;
            font-weight: 500;
            cursor: pointer;
            transition: background-color 0.3s;
            flex: 1;
            margin: 0 0.5rem;
        }

        .btn-map:first-child {
            margin-left: 0;
        }

        .btn-map:last-child {
            margin-right: 0;
        }

        .btn-select-map {
            background-color: var(--primary-color);
            color: white;
        }

        .btn-select-map:hover {
            background-color: var(--secondary-color);
        }

        .btn-manual-input {
            background-color: var(--light-gray);
            color: var(--text-color);
        }
    </style>
</head>

<body>
    <header class="header">
        <h1>校园二手市场</h1>
    </header>

    <div class="content">
        <main class="container">
            <section class="address-management">
                <h2>收货地址管理</h2>
                <div class="user-info">
                    <!-- 隐藏用户信息部分 -->
                </div>
                <div class="address-list" id="address-list">
                    <!-- 地址列表将通过JavaScript动态加载 -->
                </div>
                <button id="add-address" class="btn-add">
                    <i style="margin-right: 0.5rem;">+</i> 添加收货地址
                </button>
            </section>
        </main>
    </div>

    <nav class="nav-bar">
        <a href="index.html">
            <div class="nav-icon home-icon"></div>
            首页
        </a>
        <a href="products.html">
            <div class="nav-icon products-icon"></div>
            商品
        </a>
        <a href="publish.html">
            <div class="nav-icon publish-icon"></div>
            发布
        </a>
        <a href="news.html">
            <div class="nav-icon news-icon"></div>
            消息
        </a>
        <a href="account.html" class="active">
            <div class="nav-icon account-icon"></div>
            我的
        </a>
    </nav>

    <!-- 地址编辑模态框 -->
    <div id="addressModal" class="modal">
        <div class="modal-content">
            <span class="close">&times;</span>
            <h2 id="modalTitle">添加收货地址</h2>
            <form id="addressForm">
                <input type="hidden" id="addressId">
                <div class="form-group">
                    <label for="name">收货人姓名</label>
                    <input type="text" id="name" required>
                </div>
                <div class="form-group">
                    <label for="phone">联系电话</label>
                    <input type="tel" id="phone" required>
                </div>

                <div class="map-actions">
                    <button type="button" class="btn-map btn-select-map" id="selectMap">地图选点</button>
                    <button type="button" class="btn-map btn-manual-input" id="manualInput">手动输入</button>
                </div>

                <div class="map-container" id="mapContainer"></div>

                <div class="form-group">
                    <label for="province">省份</label>
                    <select id="province" required>
                        <option value="">请选择省份</option>
                        <!-- 省份选项将通过JavaScript动态加载 -->
                    </select>
                </div>
                <div class="form-group">
                    <label for="city">城市</label>
                    <select id="city" required>
                        <option value="">请选择城市</option>
                        <!-- 城市选项将通过JavaScript动态加载 -->
                    </select>
                </div>
                <div class="form-group">
                    <label for="district">区县</label>
                    <select id="district" required>
                        <option value="">请选择区县</option>
                        <!-- 区县选项将通过JavaScript动态加载 -->
                    </select>
                </div>
                <div class="form-group">
                    <label for="detail">详细地址</label>
                    <input type="text" id="detail" required placeholder="街道、小区、门牌号等">
                </div>
                <div class="form-group">
                    <label for="address-input">完整地址</label>
                    <input type="text" id="address-input" readonly placeholder="通过地图选点或手动输入填写">
                </div>
                <div class="form-group">
                    <label>
                        <input type="checkbox" id="isDefault"> 设为默认地址
                    </label>
                </div>
                <div class="form-actions">
                    <button type="button" class="btn-cancel" id="cancelAddress">取消</button>
                    <button type="button" class="btn-save" id="saveAddress">保存</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 引入百度地图API -->
    <script type="text/javascript"
        src="https://api.map.baidu.com/api?v=3.0&ak=zbGtUgvPbQyMOstA3sfWGdS94WYlJJBD"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            // 初始化地址数据 - 改为使用sessionStorage
            function initAddressData() {
                let addresses = JSON.parse(sessionStorage.getItem('addresses'));
                if (!addresses) {
                    addresses = {
                        shipping: []
                    };
                    sessionStorage.setItem('addresses', JSON.stringify(addresses));
                }
                return addresses;
            }

            const addresses = initAddressData();
            const addressList = document.getElementById('address-list');
            const modal = document.getElementById('addressModal');
            const modalTitle = document.getElementById('modalTitle');
            const addressForm = document.getElementById('addressForm');
            const addressIdInput = document.getElementById('addressId');
            const nameInput = document.getElementById('name');
            const phoneInput = document.getElementById('phone');
            const provinceSelect = document.getElementById('province');
            const citySelect = document.getElementById('city');
            const districtSelect = document.getElementById('district');
            const detailInput = document.getElementById('detail');
            const addressInput = document.getElementById('address-input');
            const isDefaultCheckbox = document.getElementById('isDefault');
            const saveAddressBtn = document.getElementById('saveAddress');
            const cancelAddressBtn = document.getElementById('cancelAddress');
            const addAddressBtn = document.getElementById('add-address');
            const selectMapBtn = document.getElementById('selectMap');
            const manualInputBtn = document.getElementById('manualInput');
            const mapContainer = document.getElementById('mapContainer');
            const closeBtn = document.querySelector('.close');

            // 百度地图相关变量
            let map = null;
            let marker = null;
            let geocoder = null;
            let currentPosition = null;

            // 省份数据
            const provinces = [
                '北京市', '天津市', '河北省', '山西省', '内蒙古自治区',
                '辽宁省', '吉林省', '黑龙江省', '上海市', '江苏省',
                '浙江省', '安徽省', '福建省', '江西省', '山东省',
                '河南省', '湖北省', '湖南省', '广东省', '广西壮族自治区',
                '海南省', '重庆市', '四川省', '贵州省', '云南省',
                '西藏自治区', '陕西省', '甘肃省', '青海省', '宁夏回族自治区',
                '新疆维吾尔自治区', '台湾省', '香港特别行政区', '澳门特别行政区'
            ];

            // 初始化省份选项
            provinces.forEach(province => {
                const option = document.createElement('option');
                option.value = province;
                option.textContent = province;
                provinceSelect.appendChild(option);
            });

            // 城市数据（示例：北京市）
            const citiesData = {
                '北京市': ['北京市'],
                '江苏省': ['南京市', '苏州市', '无锡市', '常州市', '徐州市', '南通市', '扬州市', '盐城市', '连云港市', '宿迁市', '淮安市', '镇江市', '泰州市', '宿迁市']
            };

            // 区县数据（示例：北京市）
            const districtsData = {
                '北京市': {
                    '北京市': ['东城区', '西城区', '朝阳区', '丰台区', '石景山区', '海淀区', '顺义区', '通州区', '大兴区', '房山区', '门头沟区', '昌平区', '平谷区', '密云区', '延庆区']
                },
                '江苏省': {
                    '南京市': ['玄武区', '秦淮区', '建邺区', '鼓楼区', '浦口区', '栖霞区', '雨花台区', '江宁区', '六合区', '溧水区', '高淳区'],
                    '苏州市': ['姑苏区', '虎丘区', '吴中区', '相城区', '吴江区', '常熟市', '张家港市', '昆山市', '太仓市']
                }
            };

            // 渲染地址列表
            function renderAddressList(addresses) {
                addressList.innerHTML = '';
                if (addresses.length === 0) {
                    const emptyMessage = document.createElement('div');
                    emptyMessage.className = 'empty-state';
                    emptyMessage.innerHTML = `
                        <i>📦</i>
                        <p>暂无收货地址</p>
                        <p>点击下方按钮添加您的第一个收货地址</p>
                    `;
                    addressList.appendChild(emptyMessage);
                    return;
                }

                addresses.forEach(address => {
                    const addressCard = document.createElement('div');
                    addressCard.className = `address-card ${address.isDefault ? 'default' : ''}`;

                    const addressHeader = document.createElement('div');
                    addressHeader.className = 'address-header';

                    const addressName = document.createElement('span');
                    addressName.className = 'address-name';
                    addressName.textContent = address.name;

                    const addressPhone = document.createElement('span');
                    addressPhone.className = 'address-phone';
                    addressPhone.textContent = address.phone;

                    if (address.isDefault) {
                        const defaultTag = document.createElement('span');
                        defaultTag.className = 'default-tag';
                        defaultTag.textContent = '默认';
                        addressHeader.appendChild(defaultTag);
                    }

                    addressHeader.appendChild(addressName);
                    addressHeader.appendChild(addressPhone);

                    const addressDetail = document.createElement('div');
                    addressDetail.className = 'address-detail';
                    addressDetail.textContent = `${address.province} ${address.city} ${address.district} ${address.detail}`;

                    const addressActions = document.createElement('div');
                    addressActions.className = 'address-actions';

                    const editBtn = document.createElement('button');
                    editBtn.className = 'btn-edit';
                    editBtn.textContent = '编辑';
                    editBtn.onclick = () => editAddress(address);

                    const deleteBtn = document.createElement('button');
                    deleteBtn.className = 'btn-delete';
                    deleteBtn.textContent = '删除';
                    deleteBtn.onclick = () => deleteAddress(address.id);

                    addressActions.appendChild(editBtn);
                    addressActions.appendChild(deleteBtn);

                    addressCard.appendChild(addressHeader);
                    addressCard.appendChild(addressDetail);
                    addressCard.appendChild(addressActions);

                    addressList.appendChild(addressCard);
                });
            }

            // 设置默认地址
            function setDefaultAddress(id) {
                const addressesData = initAddressData();

                addressesData.shipping.forEach(address => {
                    if (address.id === id) {
                        address.isDefault = true;
                    } else {
                        address.isDefault = false;
                    }
                });

                sessionStorage.setItem('addresses', JSON.stringify(addressesData));
                renderAddressList(addressesData.shipping);
            }

            // 删除地址
            function deleteAddress(id) {
                if (!confirm('确定要删除这个地址吗？')) return;

                const addressesData = initAddressData();

                addressesData.shipping = addressesData.shipping.filter(address => address.id !== id);

                // 如果删除的是默认地址，确保至少有一个默认地址
                if (addressesData.shipping.length > 0) {
                    addressesData.shipping[0].isDefault = true;
                }

                sessionStorage.setItem('addresses', JSON.stringify(addressesData));
                renderAddressList(addressesData.shipping);
            }

            // 编辑地址
            function editAddress(address) {
                showAddressModal(address);
            }

            // 初始化地图
            function initMap(position = null) {
                // 销毁之前的地图实例
                if (map) {
                    map.destroy();
                    map = null;
                }

                // 创建地图实例
                map = new BMap.Map("mapContainer");
                geocoder = new BMap.Geocoder();

                // 设置地图中心点为南昌市
                const defaultCenter = position || new BMap.Point(115.8922, 28.6765); // 南昌市中心点

                // 创建点标记
                if (marker) {
                    map.removeOverlay(marker);
                }
                marker = new BMap.Marker(defaultCenter);
                map.addOverlay(marker);

                // 设置地图中心和缩放级别
                map.centerAndZoom(defaultCenter, 15);

                // 启用拖拽标记功能
                marker.enableDragging();

                // 标记拖拽事件
                marker.addEventListener("dragend", function (e) {
                    currentPosition = e.point;
                    updateAddressFromMap(e.point);
                });

                // 点击地图事件
                map.addEventListener("click", function (e) {
                    // 移动标记到点击位置
                    marker.setPosition(e.point);
                    currentPosition = e.point;
                    updateAddressFromMap(e.point);
                });

                // 添加缩放控件
                map.addControl(new BMap.ZoomControl());
            }

            // 根据地图坐标更新地址信息
            function updateAddressFromMap(point) {
                geocoder.getLocation(point, function (rs) {
                    const addComp = rs.addressComponents;

                    // 更新省市区选择
                    provinceSelect.value = addComp.province;
                    citySelect.value = addComp.city;
                    districtSelect.value = addComp.district;

                    // 更新详细地址输入框
                    detailInput.value = rs.business || '';

                    // 更新完整地址输入框
                    addressInput.value = `${addComp.province}${addComp.city}${addComp.district}${rs.business || ''}`;

                    // 触发省市区选择变化事件
                    provinceSelect.dispatchEvent(new Event('change'));
                    setTimeout(() => {
                        citySelect.dispatchEvent(new Event('change'));
                    }, 100);
                });
            }

            // 切换地图选点和手动输入模式
            function toggleAddressInputMode(useMap) {
                if (useMap) {
                    // 显示地图，隐藏省市区选择
                    mapContainer.style.display = 'block';
                    document.querySelector('.map-actions').style.display = 'flex';
                    document.querySelectorAll('.form-group')[2].style.display = 'none'; // 隐藏省选择
                    document.querySelectorAll('.form-group')[3].style.display = 'none'; // 隐藏市选择
                    document.querySelectorAll('.form-group')[4].style.display = 'none'; // 隐藏区选择
                    document.querySelectorAll('.form-group')[5].style.display = 'none'; // 隐藏详细地址
                    document.querySelectorAll('.form-group')[6].style.display = 'none'; // 隐藏完整地址

                    // 初始化地图
                    if (!map) {
                        initMap();
                    }
                } else {
                    // 隐藏地图，显示省市区选择
                    mapContainer.style.display = 'none';
                    document.querySelector('.map-actions').style.display = 'flex';
                    document.querySelectorAll('.form-group')[2].style.display = 'flex'; // 显示省选择
                    document.querySelectorAll('.form-group')[3].style.display = 'flex'; // 显示市选择
                    document.querySelectorAll('.form-group')[4].style.display = 'flex'; // 显示区选择
                    document.querySelectorAll('.form-group')[5].style.display = 'flex'; // 显示详细地址
                    document.querySelectorAll('.form-group')[6].style.display = 'flex'; // 显示完整地址

                    // 销毁地图
                    if (map) {
                        map.destroy();
                        map = null;
                    }
                }
            }

            // 显示添加/编辑地址模态框
            function showAddressModal(address = null) {
                const isEdit = !!address;

                modalTitle.textContent = isEdit ? '编辑收货地址' : '添加收货地址';

                if (isEdit) {
                    addressIdInput.value = address.id;
                    nameInput.value = address.name;
                    phoneInput.value = address.phone;
                    provinceSelect.value = address.province;
                    citySelect.value = address.city;
                    districtSelect.value = address.district;
                    detailInput.value = address.detail;
                    addressInput.value = `${address.province}${address.city}${address.district}${address.detail}`;
                    isDefaultCheckbox.checked = address.isDefault;

                    // 如果是编辑且是默认地址，禁用设为默认复选框
                    if (address.isDefault) {
                        isDefaultCheckbox.disabled = true;
                    } else {
                        isDefaultCheckbox.disabled = false;
                    }

                    // 初始化地图（如果编辑时需要）
                    if (address.lng && address.lat) {
                        const point = new BMap.Point(address.lng, address.lat);
                        initMap(point);
                        toggleAddressInputMode(true);
                        setTimeout(() => {
                            updateAddressFromMap(point);
                        }, 300);
                    } else {
                        toggleAddressInputMode(false);
                        // 加载对应的省市区数据
                        loadCityData(address.province, address.city, address.district);
                    }
                } else {
                    addressIdInput.value = '';
                    nameInput.value = '';
                    phoneInput.value = '';
                    provinceSelect.value = '';
                    citySelect.value = '';
                    districtSelect.value = '';
                    detailInput.value = '';
                    addressInput.value = '';
                    isDefaultCheckbox.checked = false;
                    isDefaultCheckbox.disabled = false;

                    // 默认显示手动输入模式
                    toggleAddressInputMode(false);
                }

                modal.style.display = 'block';

                // 监听省份变化
                provinceSelect.addEventListener('change', function () {
                    loadCityData(this.value);
                });

                // 监听城市变化
                citySelect.addEventListener('change', function () {
                    loadDistrictData(provinceSelect.value, this.value);
                });
            }

            // 加载城市数据
            function loadCityData(province, selectedCity = '') {
                citySelect.innerHTML = '<option value="">请选择城市</option>';
                districtSelect.innerHTML = '<option value="">请选择区县</option>';

                if (province && citiesData[province]) {
                    citiesData[province].forEach(city => {
                        const option = document.createElement('option');
                        option.value = city;
                        option.textContent = city;
                        if (city === selectedCity) {
                            option.selected = true;
                        }
                        citySelect.appendChild(option);
                    });

                    // 如果传入了selectedCity，触发城市变化事件
                    if (selectedCity) {
                        loadDistrictData(province, selectedCity);
                    }
                }
            }

            // 加载区县数据
            function loadDistrictData(province, city, selectedDistrict = '') {
                districtSelect.innerHTML = '<option value="">请选择区县</option>';

                if (province && city && districtsData[province] && districtsData[province][city]) {
                    districtsData[province][city].forEach(district => {
                        const option = document.createElement('option');
                        option.value = district;
                        option.textContent = district;
                        if (district === selectedDistrict) {
                            option.selected = true;
                        }
                        districtSelect.appendChild(option);
                    });
                }
            }

            // 保存地址
            function saveAddress() {
                const name = nameInput.value.trim();
                const phone = phoneInput.value.trim();
                const province = provinceSelect.value;
                const city = citySelect.value;
                const district = districtSelect.value;
                const detail = detailInput.value.trim();
                const address = addressInput.value.trim();
                const isDefault = isDefaultCheckbox.checked;

                // 验证必填字段
                if (!name) {
                    alert('请输入收货人姓名');
                    return;
                }

                if (!phone || !/^1[3-9]\d{9}$/.test(phone)) {
                    alert('请输入有效的手机号码');
                    return;
                }

                // 根据输入模式验证地址
                if (mapContainer.style.display === 'block') {
                    // 地图选点模式
                    if (!currentPosition) {
                        alert('请在地图上选择收货位置');
                        return;
                    }
                } else {
                    // 手动输入模式
                    if (!province || !city || !district) {
                        alert('请选择完整的省市区信息');
                        return;
                    }

                    if (!detail && !address) {
                        alert('请输入详细地址');
                        return;
                    }
                }

                const addressesData = initAddressData();
                const addressId = addressIdInput.value;

                const newAddress = {
                    id: addressId || Date.now().toString(),
                    name,
                    phone,
                    province,
                    city,
                    district,
                    detail,
                    isDefault,
                    address: address || `${province}${city}${district}${detail}`,
                    lng: currentPosition ? currentPosition.lng : null,
                    lat: currentPosition ? currentPosition.lat : null
                };

                if (addressId) {
                    // 编辑现有地址
                    const index = addressesData.shipping.findIndex(a => a.id === addressId);
                    if (index !== -1) {
                        // 如果取消了默认地址，确保有其他默认地址
                        if (!isDefault && addressesData.shipping.some(a => a.isDefault && a.id !== addressId)) {
                            addressesData.shipping[index] = newAddress;
                        } else if (!isDefault) {
                            // 如果没有其他默认地址，保持当前地址为默认
                            newAddress.isDefault = true;
                            addressesData.shipping[index] = newAddress;
                        } else {
                            // 如果设为默认，先取消其他默认地址
                            if (isDefault) {
                                addressesData.shipping.forEach(a => {
                                    if (a.id !== addressId) {
                                        a.isDefault = false;
                                    }
                                });
                            } addressesData.shipping[index] = newAddress;
                        }
                    }
                } else {
                    // 添加新地址
                    if (isDefault) {
                        // 如果设为默认，先取消其他默认地址
                        addressesData.shipping.forEach(address => {
                            address.isDefault = false;
                        });
                    }
                    addressesData.shipping.push(newAddress);
                }

                sessionStorage.setItem('addresses', JSON.stringify(addressesData));
                modal.style.display = 'none';
                renderAddressList(addressesData.shipping);
            }

            // 切换地图选点和手动输入模式
            selectMapBtn.addEventListener('click', function () {
                toggleAddressInputMode(true);
                initMap();
            });

            manualInputBtn.addEventListener('click', function () {
                toggleAddressInputMode(false);
            });

            // 事件监听
            saveAddressBtn.addEventListener('click', saveAddress);
            cancelAddressBtn.addEventListener('click', () => {
                modal.style.display = 'none';
            });

            window.addEventListener('click', function (event) {
                if (event.target === modal) {
                    modal.style.display = 'none';
                }
            });

            closeBtn.addEventListener('click', () => {
                modal.style.display = 'none';
            });

            addAddressBtn.addEventListener('click', () => {
                showAddressModal();
            });

            // 初始化渲染
            renderAddressList(addresses.shipping);
        });
    </script>
</body>

</html>